<?php
/**
* @author Jelle Heemskerk <riverburn@gmail.com>, Niek Saarberg <n.saarberg@gmail.com>
* @version 0.0.3
* @package Router
* @date March 12, 2009
*
* Todo:
* - Compleet URL()
*
* Changes:
* 0.05 (Feb 24, 2011)
* - Rick v S Added function to get the current URL
*
* 0.0.4 (Match 17, 2010)
* - Rick v S replaced all "trown_new" INTO own log::write function
* 
* 0.0.3 ( February 15, 2010 )
* - Niek S. Rewrote View::baseUrl().
*           Changed View::url() comment.
*           Added View::templateUrl().
* 
* 0.0.2
* - Niek S. Added the funtion url(), this will create a url and adds the baseUrl
*   
* 0.0.1
* - Class created and added created base functionality
*/


class View {
	
    public $css_files = array();
    public $js_files  = array();
    private $registry;
    private $vars;
    private $layout     = 'default';
    private $layoutPath = 'layout';
    private $viewPath   = '';
    private $baseUrl    = null;
    private static $instance;

    public function __construct($registry) {
        
        $this->registry = $registry;
    }

	/**
	 * PHP 5.2.0 
	 * Notice: Indirect modification of overloaded property View::$foo
	 *
	 * Create reference naar var 
	 */
    public function __get($key) {
        
        return $ref = &$this->vars[$key];
    }
    
    public function __set($key, $value) {
    
        $this->vars[$key] = $value;
    }
    
    public function __isset($key) {

        return isset($this->vars[$key]);
    }
    
    public function __unset($key) {

        unset($this->vars[$key]);
    }
    
    /*--------------------------*/
    
    /**
     * Zet het pad naar view folder 
     * 
     * @access public
     * @param string $file filename
     * @return void
     */
    public function setViewPath($path) {
        
        $dir = SITE_PATH . '_modules' . DIRSEP . $path . DIRSEP;
        
        if( !is_dir($dir) ) {
            
        	log::fatal('View path not found!: ' . $dir, $this, 'setViewPath');
        }
        
        $this->viewPath = $dir;
    }
    
    /**
     * Zet het pad naar layout folder 
     * 
     * @access public
     * @param string $path path
     * @return void
     */
    public function setLayoutPath($path) {
	
        $dir = SITE_PATH . $path . DIRSEP;
       
        if(!is_dir($dir)) {
            
           log::fatal('Layout path not found!: ' . $dir, $this, 'setViewPath');
        }
        
        $this->layoutPath = $path;
       
    }
    
    /**
     * Zet het layout bestand. 
     * 
     * @access public
     * @param string $file filename
     * @return void
     */
    public function setLayout($file, $extension = '.phtml') {
    	
        $file = SITE_PATH . $this->layoutPath . DIRSEP . $file . $extension;
        
         if(!is_file($file)) {
			
         	log::fatal('Layout file not found!: ' . $file, $this, 'setLayout()');
        }

        $this->layout = $file;
    }
    
    /**
     * Haal de actieve view op. Let op, er moet altijd
     * een view aanwezig zijn.
     * 
     * @access public
     * @access void
     */
    public function loadView() {
        
        $router = $this->registry->router;
		
        /**
         * Laadt view volgens `traditionele` systeem
         */        
        $viewPath = (empty($router->route['view_path'])) ? $router->route['controller'] : rtrim($router->route['view_path'], DIRSEP);
        
        $file = SITE_PATH . 'view' . DIRSEP . $viewPath . DIRSEP . $router->route['action'] . '.php';
        
        if( !is_readable($file) ) {
        	
        	log::fatal('View file is not readable', $this, 'loadView');
            
            return;
        }
        
        include($file);
    }
    
    /**
     * Include de layout
     * 
     * @access public
     * @return void
     */
    public function show() {
        
        include $this->layout;
    }
    
    /**
	 * Include css files
	 */
    public function add_css ( $filename ) {
    	
    	if( in_array( $filename, $this->css_files ) == true ) {
    		
    		return false;
    	}
    	
    	$path = SITE_PATH . $this->layoutPath . DIRSEP . 'css' . DIRSEP . $filename;
    	
    	if( file_exists($path) == false ) {
    		
    		log::write("Css file not found. File: `$path`", $this, 'add_css()');
    		
    		return false;
    	}
    	
    	$this->css_files[] = $filename;
    }
    
    /**
	 * Include js files
	 */
    public function add_js ( $filename ) {
    	
    	if( in_array( $filename, $this->js_files ) == true ) {
    		
    		return false;
    	}
    	
    	$path = SITE_PATH . $this->layoutPath . DIRSEP . 'js' . DIRSEP . $filename;
    	
    	if( file_exists($path) == false ) {
    		
    		log::write("Js file not found. File: `$path`", $this, 'add_js()');
    		
    		return false;
    	}
    	
    	$this->js_files[] = $filename;
    }
    
    public function includeLibs () {
    	
    	$string = '';
    	
    	if($this->css_files) {
    		
	    	foreach( $this->css_files as &$css_file ) {
	    		
	    		$string .= PHP_EOL . '<link rel="stylesheet" href="' . $this->templateUrl() . '/css/' . $css_file . '" type="text/css" />';
	    	}
		}
    	
    	if($this->js_files) {
    		
	    	foreach( $this->js_files as &$js_file ) {
	    		
	    		$string .= PHP_EOL . '<script src="' . $this->templateUrl() . '/js/' . $js_file . '" type="text/javascript"></script>';
	    	}
		}
    	
    	return $string . PHP_EOL;
    }
    
    #------------- CUSTOM FUNCTIONS -------------#
    
    /**
     * Returns base url
     * 
     * @return string
     */
    public function baseUrl() {
    	
        if( $this->baseUrl ) {
            
            return $this->baseUrl;
        }
        
        $request_uri = rtrim( $_SERVER['REQUEST_URI'], '/' );
		
		$baseUrl = '';
		
    	if( isset($_GET['route']) == true ) {
			$baseUrl .= rtrim( str_replace( rtrim( $_GET['route'] , '/' ), '', $request_uri ), '/' );
			$baseUrl = explode('/?', $baseUrl);
			$baseUrl = $baseUrl[0];
		} else {
            
            $baseUrl .= $request_uri;
        }
		
		return $this->baseUrl = $baseUrl;
    }

    /**
     * Returns current URL
     * @return string
     *
     */
    public function curPageURL(){
        $pageURL = 'http://';

        if($_SERVER["SERVER_PORT"] != "80"){
            $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        }else{
            $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }

    public function templateUrl() {
		return $this->baseUrl() . '/' . $this->layoutPath;
    }
    
    /**
     * TODO!!!!
     * Passes the arguments to an url
     * As first argument use the controller then action
     * and then aditional args
     * 
     * @param array $urlParams create url from given array
     * @return string
     */
    public function url() {
		
		$url = $this->baseUrl() . '/';
		$urlArray = func_get_args();
		
		$url = $url . implode('/', $urlArray);
		
		return $url;
    }
    /*
     * Pretty simple function for refreshing the current page
     *
     */
    public function refreshPage(){
        $page = $this->curPageURL();
        header("location:$page");
        flush();
    }

	/*
	 * Gets the frontend menu
	 */
    public function getFrontMenu(){
		$sql = "SELECT `id`, `name`, `parent_id` FROM `page` WHERE `parent_id` = 0";
		$result =  DBH::getInstance()->query($sql, $this->tablePage);
		
        //mysql_fetch_object($result);

		return $result;			
	}

    public function selfURL() {
            $s = empty($_SERVER["HTTPS"]) ? ''
                : ($_SERVER["HTTPS"] == "on") ? "s"
                : "";
            $protocol = $this->strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
            $port = ($_SERVER["SERVER_PORT"] == "80") ? ""
                : (":".$_SERVER["SERVER_PORT"]);
            return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
        }

        public function strleft($s1, $s2) {
            return substr($s1, 0, strpos($s1, $s2));
        }

}